//
//  ERPageCurlView.m
//  TestWebViewPagable
//
//  Created by zhuxuhong on 2016/12/20.
//  Copyright © 2016年 zhuxh. All rights reserved.
//

#import "ERPageCurlView.h"

@implementation ERPageCurlView
{
    NSInteger _currentPageIndex; //总页数
    NSInteger _totalPageCount; //总页数
    CGFloat _beginX; //开始滑动的点x
    
    // 包含的子view
    NSArray<UIView *> *_contentViews;
    
    // 上一次卷页的进度
    CGFloat _lastProgress;
    BOOL _panFinished;
    BOOL _paning;
    CATransition *_animation;
    UIView *tempView;
    // 滑动方向
    BOOL fromRight;
}

-(instancetype)initWithFrame: (CGRect)frame
                contentViews: (NSArray* _Nonnull )contentViews{
    
    self = [super initWithFrame:frame];
    if (self) {
        _contentViews = contentViews;
        _totalPageCount = _contentViews.count;
        
        // 添加滑动手势
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(actionOfPan:)];
        [self addGestureRecognizer:pan];
        
        // 转屏通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    }
    return self;
}

-(void)deviceOrientationDidChange: (NSNotification*)noti{
    [self resetSubviews];
}

// 重设frame
-(void)resetSubviews{
    for (UIView *v in _contentViews) {
        v.frame = self.bounds;
    }
}

-(void)setCurrentPageIndex:(NSInteger)current{
    if (_contentViews.count == 0) {
        return;
    }
    if (current < 0) {
        current = 0;
    }
    else if (current > _contentViews.count-1) {
        current = _contentViews.count-1;
    }
    _currentPageIndex = current;
    [self addSubview:[self currentPageView]];
}

-(void)actionOfPan: (UIPanGestureRecognizer*)pan{
    //1. 判断滑动方向
    CGPoint translation = [pan translationInView:self];
    if (translation.x == 0) {
        return;
    }
    
    //向左
    if (translation.x < 0) {
        fromRight = true;
    }
    
    NSLog(@"x: %f",translation.x);
    
    //2. 滑动条件判断
    if (!fromRight && _currentPageIndex == 0) { //向右滑动，是第一页，返回
        return;
    }
    else if(fromRight && _currentPageIndex == _totalPageCount-1){ //向左滑动，是最后一页，返回
        return;
    }
    
    //3. 改变frame
    if (!fromRight) { //向右
        tempView = _contentViews[_currentPageIndex-1];
        [self.layer addSublayer:tempView.layer];
    }
    else{ //向左
        tempView = _contentViews[_currentPageIndex];
        [self.layer insertSublayer: _contentViews[_currentPageIndex+1].layer below:tempView.layer];
    }
    CGRect frame = tempView.frame;
    CGPoint location = [pan locationInView:self];
    CGFloat x = location.x;
    CGFloat w = CGRectGetWidth(frame);
    if (fromRight && _beginX == 0) {
        _beginX = CGRectGetMaxX(frame) - x;
    }
    _lastProgress = fabs(x +_beginX - w) / w;
    if (pan.state == UIGestureRecognizerStateBegan) {
        _panFinished = false;
        _paning = true;
        [self animationWithStartProgress:_lastProgress endProgress:_lastProgress duration:0];
    }
    else if (pan.state == UIGestureRecognizerStateChanged) {
        [self animationWithStartProgress:_lastProgress endProgress:_lastProgress duration:0];
    }
    else if(pan.state == UIGestureRecognizerStateEnded){
        
        if (fromRight) { //向左
            [self animationWithStartProgress:_lastProgress endProgress:1 duration:0.5];
            _currentPageIndex += 1;
        }
        else{
            [self animationWithStartProgress:_lastProgress endProgress:0 duration:0.5];
            _currentPageIndex -= 1;
            tempView = _contentViews[_currentPageIndex+1];
        }
        
        _beginX = 0;
        _panFinished = true;
        _paning = false;
        _lastProgress = 0;
        fromRight = false;
    }
}

-(void)animationWithStartProgress: (CGFloat)start
                      endProgress: (CGFloat)end
                         duration: (CFTimeInterval)duration{
    
    if (!_animation) {
        _animation = [CATransition animation];
        _animation.timingFunction = UIViewAnimationCurveEaseInOut;
        _animation.type = @"pageCurl";
    }
    _animation.delegate = self;
    _animation.startProgress = start;
    _animation.endProgress = end;
    _animation.duration = duration;
    _animation.subtype = @"fromRight";
    [tempView.layer addAnimation:_animation forKey:@"animation"];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if (_paning && !_panFinished) {
        [tempView.layer removeAllAnimations];
        [self animationWithStartProgress:_lastProgress endProgress:_lastProgress duration:1000000000000000];
    }
    else if(!_paning && !_panFinished){
        [tempView removeFromSuperview];
    }
}

-(UIView*)currentPageView{
    return _contentViews[_currentPageIndex];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
